from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User

import app_settings
from forms import FormEntry, FormFindFriend, FormConnection
from models import Entry, Connection, CONNECTION_WAITING, CONNECTION_ACCEPTED,\
        CONNECTION_BLOCKED
from feeds import FeedLatestEntriesRss, FeedLatestEntriesAtom

def index(request):
    MICROBLOG_URL_BASE = app_settings.MICROBLOG_URL_BASE

    form_entry = FormEntry()
    form_connect = FormFindFriend()

    if request.user.is_authenticated():
        entries = request.user.received_entries.all()[:app_settings.MICROBLOG_ENTRIES_LIMIT]
        connections = request.user.connections_from.all()
        connections_show_actions = True

    return render_to_response(
            'microblog/index.html',
            locals(),
            context_instance=RequestContext(request),
            )

@login_required
def entry_edit(request, entry_id=None):
    MICROBLOG_URL_BASE = app_settings.MICROBLOG_URL_BASE

    if entry_id:
        entry = get_object_or_404(Entry, id=entry_id)
    else:
        entry = None

    if request.POST:
        form = FormEntry(request.POST, instance=entry)

        if form.is_valid():
            entry = form.save(False)
            entry.user = request.user
            entry.save()

            if entry:
                return HttpResponseRedirect(app_settings.MICROBLOG_URL_BASE)
    else:
        form = FormEntry(instance=entry)

    return render_to_response(
            'microblog/entry_edit.html',
            locals(),
            context_instance=RequestContext(request),
            )

def find_friend(request):
    MICROBLOG_URL_BASE = app_settings.MICROBLOG_URL_BASE

    if request.GET:
        form = FormFindFriend(request.GET)

        if form.is_valid():
            found_users = form.find()

            if found_users.count() == 1:
                return HttpResponseRedirect(found_users[0].get_absolute_url())
    else:
        form = FormFindFriend()

    return render_to_response(
            'microblog/find_friend.html',
            locals(),
            context_instance=RequestContext(request),
            )

@login_required
def connection_add(request, username):
    friend = get_object_or_404(User, username=username)

    connection, new = Connection.objects.get_or_create(
            user=request.user,
            friend=friend,
            defaults={
                'status': CONNECTION_ACCEPTED,
                }
            )

    if not new:
        request.user.message_set.create(message=_('You are already connected to this user!'))
    
    return HttpResponseRedirect(app_settings.MICROBLOG_URL_BASE)

@login_required
def connection_accept(request, connection_id):
    connection = get_object_or_404(Connection, id=connection_id)
    connection.status = CONNECTION_ACCEPTED
    connection.save()

    request.user.message_set.create(message=_('Connection accepted!'))

    return HttpResponseRedirect(
            request.META.get('HTTP_REFERER', app_settings.MICROBLOG_URL_BASE)
            )

@login_required
def connection_block(request, connection_id):
    connection = get_object_or_404(Connection, id=connection_id)
    connection.status = CONNECTION_BLOCKED
    connection.save()

    request.user.message_set.create(message=_('Connection blocked!'))

    return HttpResponseRedirect(
            request.META.get('HTTP_REFERER', app_settings.MICROBLOG_URL_BASE)
            )

@login_required
def connection_delete(request, connection_id):
    connection = get_object_or_404(Connection, id=connection_id)
    connection.delete()

    request.user.message_set.create(message=_('Connection deleted!'))

    return HttpResponseRedirect(
            request.META.get('HTTP_REFERER', app_settings.MICROBLOG_URL_BASE)
            )

def user_details(request, username):
    MICROBLOG_URL_BASE = app_settings.MICROBLOG_URL_BASE

    home_user = get_object_or_404(User, username=username)
    connections = home_user.connections_from.filter(status=CONNECTION_ACCEPTED)

    return render_to_response(
            'microblog/user_details.html',
            locals(),
            context_instance=RequestContext(request),
            )

def user_feeds(request, username, url):
    home_user = get_object_or_404(User, username=username)

    try:
        slug, params = url.split('/')
    except ValueError:
        slug, params = url, ''

    if slug == 'rss':
        feed = FeedLatestEntriesRss(home_user, slug, request)
    else:
        feed = FeedLatestEntriesAtom(home_user, slug, request)

    feedgen = feed.get_feed(params)
    ret = HttpResponse(mimetype=feedgen.mime_type)
    feedgen.write(ret, 'utf-8')

    return ret

